<form
  lay-filter="deliveryRecordForm"
  id="deliveryRecordForm"
  class="layui-form open-form"
>
  <div class="open-model" id="deliveryRecordFormContent">
    <div class="open-auto">
      <input name="id" type="hidden" />
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">发货类型</label>
          <div class="layui-input-block">
            <input name="typeCode" id="typeCode" type="hidden" />
            <select id="typeId" name="typeId" lay-filter="typeId"></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">订单编号</label>
          <div class="layui-input-block" id="saleOrderIdBox">
            <input
              name="saleOrderId"
              id="saleOrderId"
              disabled
              class="layui-input"
              type="hidden"
            />
            <input
              id="saleOrderCode"
              name="saleOrderCode"
              class="layui-input"
            />
            <!-- <select
              id="saleOrderId"
              name="saleOrderId"
              lay-filter="saleOrderId"
            ></select> -->
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">客户名称/部门</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="customerName"
              disabled
              class="layui-input adv-disable"
            />
            <input
              name="customerId"
              type="hidden"
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <!-- <div class="layui-col-xs3">
          <div class="layui-form-item">
            <label class="layui-form-label">订单编号/制造令</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="zhizao"
                disabled
                class="layui-input adv-disable"
              />
            </div>
          </div>
        </div> -->
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">录入时间</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="orderCreateTime"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">计划交付时间</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="orderPlanOnTime"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <!-- <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">发货仓库类型</label>
          <div class="layui-input-block">
            <select id="warehouseTypeId" name="warehouseTypeId" lay-filter="warehouseTypeId"></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">发货仓库</label>
          <div class="layui-input-block">
            <select id="warehouseId" name="warehouseId" lay-filter="warehouseId"></select>
          </div>
        </div>
      </div> -->
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">物流方式</label>
          <div class="layui-input-block">
            <select
              id="logistics"
              name="logistics"
              lay-filter="logistics"
            ></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">物流/快递公司</label>
          <div class="layui-input-block">
            <select
              id="companyId"
              name="companyId"
              lay-filter="companyId"
            ></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">物流单号</label>
          <div class="layui-input-block">
            <input type="text" name="expressCode" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">物流联系人</label>
          <div class="layui-input-block">
            <input type="text" name="customerConcat" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">物流电话</label>
          <div class="layui-input-block">
            <input type="text" name="customerMoble" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">车牌号</label>
          <div class="layui-input-block">
            <input type="text" name="carNo" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">运费结算方式</label>
          <div class="layui-input-block">
            <select
              id="transportSettlementId"
              name="transportSettlementId"
              lay-filter="transportSettlementId"
            >
              <option value=""></option>
              <option value="times">按次结算</option>
              <option value="mouth">月结</option>
            </select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">运费(元)</label>
          <div class="layui-input-block">
            <input type="text" name="transportExpenses" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">备注</label>
          <div class="layui-input-block">
            <input type="text" name="remark" class="layui-input" />
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <button class="layui-btn" type="button" id="Configure">
          选择签收物料信息
        </button>
        <table
          class="layui-table"
          id="deliveryRecordFormTable"
          lay-filter="deliveryRecordFormTable"
        ></table>
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button
        class="layui-btn layui-btn-primary"
        type="button"
        ew-event="closeDialog"
      >
        关闭
      </button>
      <button
        class="layui-btn"
        lay-filter="formSubmit"
        type="button"
        lay-submit
      >
        提交
      </button>
    </div>
  </div>
</form>

<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };
      const data = nowData.data;
      //入库类型
      var inventoryType;
      let deliveryRecordProductList = [];
      if (nowData.eventName === "detail") {
        admin.setFormDisable("#deliveryRecordFormContent", true);
        $("#Configure").hide();
      }
      //入库类型列表
      await admin.getDictListPro("logistics", "logistics_type", "物流方式");
      await admin.initDataSelectPro(
        "enterprise/invoicing/admin/transportCompany/list",
        {},
        "companyId",
        "物流快递公司"
      );
      await admin.initDataSelectPro(
        "enterprisecab/warehouse/admin/warehouseInventoryType/list",
        { inventoryType: "out", limit: 9999, status: "enable", ids: "3,4" },
        "typeId",
        "发货类型",
        async function (selectData, obj) {
          inventoryType = obj;
          table.reload("deliveryRecordFormTable", {
            data: [],
          });
          $("#saleOrderId").empty();
          form.val("deliveryRecordForm", {
            saleOrderId: "",
            customerName: "",
            customerId: "",
            orderPlanOnTime: "",
            orderCreateTime: "",
            logisticsNo: "",
            typeCode: "",
            saleOrderCode: "",
          });
          console.log(22,obj);
          
          $("#typeCode").val(obj.code);
          form.val("deliveryRecordForm",{
            typeCode:obj.code
          })
          console.log(form.val("deliveryRecordForm"));
          
          form.render("select");

          //出入库类型编码-赋值
          // if (selectData.value) {
          //   if (obj.code == "CPC") {
          //     await admin.initDataSelectPro(
          //       "enterprise/sell/admin/finishedOrder/list",
          //       {
          //         selStatus: 3,
          //         limit: 99999,
          //       },
          //       "saleOrderId",
          //       "销售成品订单",
          //       (d, obj) => {
          //         form.val("deliveryRecordForm", {
          //           customerName: "",
          //           customerId: "",
          //           orderPlanOnTime: "",
          //           orderCreateTime: "",
          //           logisticsNo: "",
          //         });
          //         form.val("deliveryRecordForm", {
          //           ...obj,
          //           orderCreateTime: obj.createTime,
          //           orderPlanOnTime: obj.planOnTime,
          //         });
          //       },
          //       "selCode"
          //     );
          //   } else if (obj.code === "SCDC") {
          //     await admin.initDataSelectPro(
          //       "enterprise/sell/admin/massOrder/list",
          //       {
          //         limit: 99999,
          //       },
          //       "saleOrderId",
          //       "生产订单",
          //       (d, obj) => {
          //         form.val("deliveryRecordForm", {
          //           customerName: "",
          //           orderPlanOnTime: "",
          //           customerId: "",
          //           orderCreateTime: "",
          //           logisticsNo: "",
          //         });
          //         form.val("deliveryRecordForm", {
          //           ...obj,
          //           orderCreateTime: obj.createTime,
          //           orderPlanOnTime: obj.deliveryTime,
          //         });
          //       },
          //       "code"
          //     );
          //   }
          // } else {
          //   $("#typeId").val("");
          // }
        }
      );
      $("#saleOrderIdBox").click(function () {
        if (!$("#typeCode").val()) {
          layer.msg("请先选择发货类型");
          return;
        }
        openFormByOrder($("#typeCode").val());
      });
      function openFormByOrder(type) {
        let url = "";
        let title = "";
        let orderPlanOnTime=''
        if (type == "CPC") {
          title = "成品销售订单列表";
          path = "components/sell/finishedOrder.html";
          orderPlanOnTime='planOnTime'
        } else if (type == "SCDC") {
          title = "量产订单列表";
          path = "components/sell/massOrder.html";
          orderPlanOnTime='deliveryTime'
        }
        admin.formOpen({
          title: title,
          area: ["90%", "80%"],
          path: path,
          success: function () {
            parentData.eventName = "radio";
          },
          end: function () {
            // form.val("addProductionPlanFormDiv", { ...orderObj });
            console.log(childData.list);
            if (childData.list && childData.list.length > 0) {
              let obj = childData.list[0];
              console.log("obj", obj);
              form.val("deliveryRecordForm", {
                saleOrderCode: obj.code,
                saleOrderId: obj.id,
                ...obj,
                orderCreateTime: obj.createTime,
                orderPlanOnTime: obj[orderPlanOnTime],
              })
              // form.val("addProductionPlanFormDiv", {
              //   orderId: obj.id,
              //   orderCode: obj.code,
              //   shipmentTime: obj.deliveryTime,
              // });
            }
          },
        });
      }

      // await admin.initDataSelectPro(
      //   "enterprisecab/warehouse/admin/warehouseType/list",
      //   {},
      //   "warehouseTypeId",
      //   "仓库类型",
      //   async (d) => {
      //     await admin.initDataSelectPro(
      //       "enterprisecab/warehouse/admin/warehouse/list",
      //       {
      //         warehouseTypeId: d.value,
      //       },
      //       "warehouseId",
      //       "仓库",
      //       (d) => {
      //         table.reload("deliveryRecordFormTable", {
      //           data: [],
      //         });
      //       }
      //     );
      //   }
      // );
      // ['typeId', 'saleOrderId', 'warehouseTypeId', 'warehouseId'].forEach((field) => {
      //   form.on(`select(${field})`, function (data) {
      //     table.reload('deliveryRecordFormTable', {
      //       data: [],
      //     });
      //   });
      // });
      table.render({
        elem: "#deliveryRecordFormTable",
        data: [],
        page: false,
        cellMinWidth: 100,
        cols: [
          [
            { type: "numbers", align: "center", height: 70, title: "序号" },
            {
              field: "skuCode",
              align: "center",
              title: "产品编号",
              width: 120,
            },
            { field: "skuName", align: "center", title: "规格码", width: 120 },
            {
              field: "cusProductCode",
              align: "center",
              title: "客户产品编码",
              width: 120,
            },
            { field: "quantity", align: "center", title: "计划交付量" },
            { field: "selRemainQuality", align: "center", title: "交付剩余量" },
            { field: "mainUnitName", align: "center", title: "单位" },
            { field: "haveQuantity", align: "center", title: "可用库存" },
            {
              field: "shipmentQty",
              align: "center",
              title: "发货数量",
              templet: admin.setTableInput(
                "shipmentQty",
                nowData.eventName === "detail",
                "shipmentQty"
              ),
            },
            {
              field: "currentCostPrice",
              align: "center",
              title: "单价",
            },
            {
              field: "subtotalAmount",
              align: "center",
              title: "总价",
            },
            {
              field: "surplusSignQuantity",
              align: "center",
              title: "备注",
            },
            {
              align: "center",
              title: "操作",
              hide: nowData.eventName === "detail",
              width: 100,
              fixed: "right",
              templet: function (d) {
                return `<button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>`;
              },
            },
          ],
        ],
        done: function () {
          // 监听输入框-签收数量
          admin.tableInputChangeByClass(
            "deliveryRecordFormTable",
            "shipmentQty",
            (index, value, tableData, field, tableId) => {
              console.log(index, value, tableData, field, tableId);
              admin.tableProduct(
                tableId,
                index,
                ["shipmentQty", "currentCostPrice"],
                "subtotalAmount"
              );
            }
          );
        },
      });
      if (data && data.id) {
        if (data.typeCode === "CPC") {
          await admin.initDataSelectPro(
            "enterprise/sell/admin/finishedOrder/list",
            {
              selStatus: 3,
              limit: 99999,
            },
            "saleOrderId",
            "销售成品订单",
            (d, obj) => {
              form.val("deliveryRecordForm", obj);
            },
            "selCode"
          );
        } else if (data.typeCode === "SCDC") {
          await admin.initDataSelectPro(
            "enterprise/sell/admin/massOrder/list",
            {
              limit: 99999,
            },
            "saleOrderId",
            "生产订单",
            null,
            "code"
          );
        }
        await admin.initDataSelectPro(
          "enterprisecab/warehouse/admin/warehouse/list",
          {
            warehouseTypeId: data.warehouseTypeId,
          },
          "warehouseId",
          "仓库"
        );
        form.val("deliveryRecordForm", data);
        form.render("select");
        table.reload("deliveryRecordFormTable", {
          data: data.deliveryRecordDetails,
        });
      }

      $("#Configure").click(function () {
        let saleOrderId = $("#saleOrderId").val();
        let warehouseId = $("#warehouseId").val();
        let typeCode = $("#typeCode").val();
        const urlBuTypeObj = {
          CPC: "enterprise/sell/admin/finishedOrder/getSkuInfo/", //成品销售
          SCDC: "enterprise/sell/admin/order/getSkuInfo/", // 生产订单
        };
        if (saleOrderId) {
          admin.req(
            "enterprise/sell/admin/deliveryRecord/getSkuInfoByType",
            {
              type: typeCode,
              orderId: saleOrderId,
              // warehouseId: warehouseId,
            },
            (res) => {
              if (res.code === 200) {
                if (res.data && res.data.length > 0) {
                  admin.formOpen({
                    area: ["90%", "85%"],
                    offset: "50px",
                    title: "添加出库发货计划",
                    path: "components/sell/deliveryRecordFormTable.html",
                    success: function () {
                      parentData.list = res.data;
                    },
                    end: function () {
                      table.reload("deliveryRecordFormTable", {
                        data: childData.list,
                      });
                    },
                  });
                } else {
                  layer.msg("当前系统下没有该订单的物料信息");
                }
              } else {
                layer.msg(res.msg);
              }
            },
            "POST"
          );
        } else {
          layer.msg("请先选择订单号和仓库");
        }
      });
      table.on("tool(deliveryRecordFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["deliveryRecordFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("deliveryRecordFormTable", {
            data: list,
          });
        }
      });
      form.on("submit(formSubmit)", function (d) {
        const formData = { ...d.field };
        if (
          table.cache["deliveryRecordFormTable"].some((v) => {
            return v.shipmentQty - v.haveQuantity > 0;
          })
        ) {
          console.log(
            table.cache["deliveryRecordFormTable"].filter((v) => {
              return v.shipmentQty - v.haveQuantity > 0;
            })
          );
          layer.msg("发货数量不能大于库存数量");
          return false;
        }
        if (
          table.cache["deliveryRecordFormTable"].some((v) => {
            return v.shipmentQty - v.selRemainQuality > 0;
          })
        ) {
          layer.msg("发货数量不能大于交付剩余数");
          return false;
        }
        formData.deliveryRecordDetails = table.cache["deliveryRecordFormTable"];

        admin.req(
          "enterprise/sell/admin/deliveryRecord/addDeliveryInfo",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code === 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("deliveryRecordTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "POST",
          false,
          "application/json"
        );
        // if (nowData.eventName == 'add') {
        //     admin.req('enterprise/purchase/admin/deliveryRecord/add', JSON.stringify(formData), function (res) {
        //         layer.closeAll('loading');
        //         if (res.code == 200) {
        //             layer.msg(res.msg, {icon: 1});
        //             table.reload('deliveryRecordTable');
        //             layer.closeAll('page');
        //         } else {
        //             layer.msg(res.msg, {icon: 2});
        //         }
        //     }, 'POST', false, "application/json");
        // }
      });
    }
  );
</script>

<style>
  #deliveryRecordForm .layui-form-label {
    width: 110px;
  }

  #deliveryRecordForm .layui-input-block {
    margin-left: 140px;
  }

  #deliveryRecordForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
